package com.sakura.takeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.takeaway.common.BaseContext;
import com.sakura.takeaway.common.R;
import com.sakura.takeaway.entity.OrderDetail;
import com.sakura.takeaway.entity.Orders;
import com.sakura.takeaway.entity.OrdersDto;
import com.sakura.takeaway.service.OrderDetailService;
import com.sakura.takeaway.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Sakura
 * @Date 2022-07-15 18:40
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据，{}",orders);

        ordersService.submit(orders);

        return R.success("下单成功");
    }

    /**
     * 订单明细
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String number,String beginTime,String endTime){

        //构造分页构造器
        Page<Orders> pageInfo =new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper =new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number!=null,Orders::getNumber,number);
        //范围查询的动态SQL
        queryWrapper.gt(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime);
        queryWrapper.lt(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        ordersService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 修改订单状态
     * @param map
     * @return
     */
    @PutMapping
    public R<String> orderStatusChange(@RequestBody Map<String,String> map){

        //获取订单id
        String id = map.get("id");
        Long orderId = Long.parseLong(id);
        //获当前状态
        Integer status = Integer.parseInt(map.get("status"));

        //判断
        if (orderId == null || status==null){
            return R.error("传入信息不合法");
        }

        Orders orders = ordersService.getById(orderId);
        orders.setStatus(status);
        ordersService.updateById(orders);

        return R.success("订单状态修改成功");

    }

    //抽离的一个方法，通过订单id查询订单明细，得到一个订单明细的集合
    //这里抽离出来是为了避免在stream中遍历的时候直接使用构造条件来查询导致eq叠加，从而导致后面查询的数据都是null
    public List<OrderDetail> getOrderDetailListByOrderId(Long orderId){
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        return orderDetailList;
    }
    /**
     * 用户查询历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize){

        //构造分页对象
        Page<Orders> pageInfo =new Page<>();
        Page<OrdersDto> dtoPage =new Page<>();

        //构造查询条件
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        //添加用户id作为查询条件，否则会出现用户可以查询到其他用户的订单情况
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        //更新时间降序排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo,queryWrapper);

        //通过OrderId查询对应的OrderDetail
        LambdaQueryWrapper<OrderDetail> queryWrapper2=new LambdaQueryWrapper<>();
        //对OrderDto进行需要的属性赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtoList=records.stream().map((item)->{
            OrdersDto ordersDto =new OrdersDto();
            //获取订单id
            Long orderId = item.getId();
            List<OrderDetail> orderDetailList = this.getOrderDetailListByOrderId(orderId);
            //对象拷贝
            BeanUtils.copyProperties(item,ordersDto);
            //对orderDto进行OrderDetails属性的赋值
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        dtoPage.setRecords(ordersDtoList);

        return R.success(dtoPage);
    }
}
